import { STAT_COLORS } from "@/constant";
import { FC, useMemo } from "react";
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";
import { QuestionRadioStatPropsType } from "./interface";

const format = (n: number) => (n * 100).toFixed(2);

const StatComponent: FC<QuestionRadioStatPropsType> = (props) => {
  const { stat = [] } = props;
  const sum = useMemo(() => stat.reduce((c, n) => c + n.count, 0), [stat]);

  return (
    <div style={{ width: "300px", height: "400px" }}>
      <ResponsiveContainer width="100%" height="100%">
        <PieChart margin={{ left: 20 }}>
          <Pie
            dataKey="count"
            data={stat}
            cx="50%" // x 轴的偏移
            cy="50%" // y 轴的偏移
            outerRadius={40} // 饼图的直径
            fill="#8884d8"
            label={(i) => `${i.name}: ${format(i.count / sum)}%`}
          >
            {stat.map((_, index) => (
              <Cell key={index} fill={STAT_COLORS[index]} />
            ))}
          </Pie>
          <Tooltip />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
};

export default StatComponent;
